import { createSlice, PayloadAction } from '@reduxjs/toolkit';

// 主题类型
export type ThemeMode = 'light' | 'dark' | 'auto';

// 侧边栏状态
export interface SidebarState {
  collapsed: boolean;
  width: number;
  collapsedWidth: number;
}

// 面包屑项
export interface BreadcrumbItem {
  title: string;
  path?: string;
}

// 通知项
export interface NotificationItem {
  id: string;
  type: 'success' | 'info' | 'warning' | 'error';
  title: string;
  message: string;
  duration?: number;
  timestamp: number;
}

// 模态框状态
export interface ModalState {
  [key: string]: {
    visible: boolean;
    data?: any;
    loading?: boolean;
  };
}

// UI状态接口
interface UIState {
  // 主题
  theme: ThemeMode;
  
  // 侧边栏
  sidebar: SidebarState;
  
  // 页面加载状态
  pageLoading: boolean;
  
  // 面包屑
  breadcrumbs: BreadcrumbItem[];
  
  // 通知
  notifications: NotificationItem[];
  
  // 模态框
  modals: ModalState;
  
  // 全局搜索
  globalSearch: {
    visible: boolean;
    keyword: string;
    results: any[];
    loading: boolean;
  };
  
  // 设置面板
  settingsPanel: {
    visible: boolean;
  };
  
  // 移动端
  mobile: {
    sidebarVisible: boolean;
  };
  
  // 页面配置
  pageConfig: {
    showHeader: boolean;
    showSidebar: boolean;
    showFooter: boolean;
    contentPadding: boolean;
  };
  
  // 表格配置
  tableConfig: {
    pageSize: number;
    showSizeChanger: boolean;
    showQuickJumper: boolean;
    showTotal: boolean;
  };
}

// 初始状态
const initialState: UIState = {
  theme: (localStorage.getItem('admin_theme') as ThemeMode) || 'light',
  sidebar: {
    collapsed: localStorage.getItem('admin_sidebar_collapsed') === 'true',
    width: 240,
    collapsedWidth: 80,
  },
  pageLoading: false,
  breadcrumbs: [],
  notifications: [],
  modals: {},
  globalSearch: {
    visible: false,
    keyword: '',
    results: [],
    loading: false,
  },
  settingsPanel: {
    visible: false,
  },
  mobile: {
    sidebarVisible: false,
  },
  pageConfig: {
    showHeader: true,
    showSidebar: true,
    showFooter: true,
    contentPadding: true,
  },
  tableConfig: {
    pageSize: parseInt(localStorage.getItem('admin_table_page_size') || '20'),
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: true,
  },
};

// 创建slice
const uiSlice = createSlice({
  name: 'ui',
  initialState,
  reducers: {
    // 设置主题
    setTheme: (state, action: PayloadAction<ThemeMode>) => {
      state.theme = action.payload;
      localStorage.setItem('admin_theme', action.payload);
    },
    
    // 切换侧边栏折叠状态
    toggleSidebar: (state) => {
      state.sidebar.collapsed = !state.sidebar.collapsed;
      localStorage.setItem('admin_sidebar_collapsed', state.sidebar.collapsed.toString());
    },
    
    // 设置侧边栏折叠状态
    setSidebarCollapsed: (state, action: PayloadAction<boolean>) => {
      state.sidebar.collapsed = action.payload;
      localStorage.setItem('admin_sidebar_collapsed', action.payload.toString());
    },
    
    // 设置页面加载状态
    setPageLoading: (state, action: PayloadAction<boolean>) => {
      state.pageLoading = action.payload;
    },
    
    // 设置面包屑
    setBreadcrumbs: (state, action: PayloadAction<BreadcrumbItem[]>) => {
      state.breadcrumbs = action.payload;
    },
    
    // 添加通知
    addNotification: (state, action: PayloadAction<Omit<NotificationItem, 'id' | 'timestamp'>>) => {
      const notification: NotificationItem = {
        ...action.payload,
        id: Date.now().toString(),
        timestamp: Date.now(),
      };
      state.notifications.unshift(notification);
      
      // 限制通知数量
      if (state.notifications.length > 50) {
        state.notifications = state.notifications.slice(0, 50);
      }
    },
    
    // 移除通知
    removeNotification: (state, action: PayloadAction<string>) => {
      state.notifications = state.notifications.filter(n => n.id !== action.payload);
    },
    
    // 清空通知
    clearNotifications: (state) => {
      state.notifications = [];
    },
    
    // 显示模态框
    showModal: (state, action: PayloadAction<{ key: string; data?: any }>) => {
      const { key, data } = action.payload;
      state.modals[key] = {
        visible: true,
        data,
        loading: false,
      };
    },
    
    // 隐藏模态框
    hideModal: (state, action: PayloadAction<string>) => {
      const key = action.payload;
      if (state.modals[key]) {
        state.modals[key].visible = false;
      }
    },
    
    // 设置模态框加载状态
    setModalLoading: (state, action: PayloadAction<{ key: string; loading: boolean }>) => {
      const { key, loading } = action.payload;
      if (state.modals[key]) {
        state.modals[key].loading = loading;
      }
    },
    
    // 显示全局搜索
    showGlobalSearch: (state) => {
      state.globalSearch.visible = true;
    },
    
    // 隐藏全局搜索
    hideGlobalSearch: (state) => {
      state.globalSearch.visible = false;
      state.globalSearch.keyword = '';
      state.globalSearch.results = [];
    },
    
    // 设置全局搜索关键词
    setGlobalSearchKeyword: (state, action: PayloadAction<string>) => {
      state.globalSearch.keyword = action.payload;
    },
    
    // 设置全局搜索结果
    setGlobalSearchResults: (state, action: PayloadAction<any[]>) => {
      state.globalSearch.results = action.payload;
    },
    
    // 设置全局搜索加载状态
    setGlobalSearchLoading: (state, action: PayloadAction<boolean>) => {
      state.globalSearch.loading = action.payload;
    },
    
    // 显示设置面板
    showSettingsPanel: (state) => {
      state.settingsPanel.visible = true;
    },
    
    // 隐藏设置面板
    hideSettingsPanel: (state) => {
      state.settingsPanel.visible = false;
    },
    
    // 切换移动端侧边栏
    toggleMobileSidebar: (state) => {
      state.mobile.sidebarVisible = !state.mobile.sidebarVisible;
    },
    
    // 设置移动端侧边栏状态
    setMobileSidebarVisible: (state, action: PayloadAction<boolean>) => {
      state.mobile.sidebarVisible = action.payload;
    },
    
    // 设置页面配置
    setPageConfig: (state, action: PayloadAction<Partial<UIState['pageConfig']>>) => {
      state.pageConfig = { ...state.pageConfig, ...action.payload };
    },
    
    // 设置表格配置
    setTableConfig: (state, action: PayloadAction<Partial<UIState['tableConfig']>>) => {
      state.tableConfig = { ...state.tableConfig, ...action.payload };
      
      // 保存页面大小到本地存储
      if (action.payload.pageSize) {
        localStorage.setItem('admin_table_page_size', action.payload.pageSize.toString());
      }
    },
    
    // 重置UI状态
    resetUI: (state) => {
      state.pageLoading = false;
      state.breadcrumbs = [];
      state.notifications = [];
      state.modals = {};
      state.globalSearch = {
        visible: false,
        keyword: '',
        results: [],
        loading: false,
      };
      state.settingsPanel.visible = false;
      state.mobile.sidebarVisible = false;
    },
  },
});

// 导出actions
export const {
  setTheme,
  toggleSidebar,
  setSidebarCollapsed,
  setPageLoading,
  setBreadcrumbs,
  addNotification,
  removeNotification,
  clearNotifications,
  showModal,
  hideModal,
  setModalLoading,
  showGlobalSearch,
  hideGlobalSearch,
  setGlobalSearchKeyword,
  setGlobalSearchResults,
  setGlobalSearchLoading,
  showSettingsPanel,
  hideSettingsPanel,
  toggleMobileSidebar,
  setMobileSidebarVisible,
  setPageConfig,
  setTableConfig,
  resetUI,
} = uiSlice.actions;

// 选择器
export const selectUI = (state: { ui: UIState }) => state.ui;
export const selectTheme = (state: { ui: UIState }) => state.ui.theme;
export const selectSidebar = (state: { ui: UIState }) => state.ui.sidebar;
export const selectPageLoading = (state: { ui: UIState }) => state.ui.pageLoading;
export const selectBreadcrumbs = (state: { ui: UIState }) => state.ui.breadcrumbs;
export const selectNotifications = (state: { ui: UIState }) => state.ui.notifications;
export const selectModals = (state: { ui: UIState }) => state.ui.modals;
export const selectGlobalSearch = (state: { ui: UIState }) => state.ui.globalSearch;
export const selectSettingsPanel = (state: { ui: UIState }) => state.ui.settingsPanel;
export const selectMobile = (state: { ui: UIState }) => state.ui.mobile;
export const selectPageConfig = (state: { ui: UIState }) => state.ui.pageConfig;
export const selectTableConfig = (state: { ui: UIState }) => state.ui.tableConfig;

// 导出reducer
export default uiSlice.reducer;
